<?php
/**
 * 客户订单明细
 * (model)
 */

namespace App\Models\CustomerDelivery;

use App\Models\Product\ProductSku;
use Illuminate\Database\Eloquent\Model;

class CustomerOrderDetails extends Model
{
    protected $table = 'customer_order_detail';

    protected $guarded  = [];

    /**
     * erp订单同步状态
     * @var string[]
     */
    const SYNC_NO = 1; //未同步
    const SYNC_YES = 2; //已同步
    const SYNC_ERROR = 3; //同步异常
    public static $_erpSync = [
        1 => '未同步',
        2 => '已同步',
        3 => '同步异常',
    ];

    /**
     * 申请状态
     * @var string[]
     */
    const ORDER_DELIVERY_NO     = 1; //未申请发货
    const ORDER_DELIVERY_PART   = 2; //部分申请发货
    const ORDER_DELIVERY_YES    = 3; //完全申请发货
    const ORDER_DELIVERY_CANCEL = 4; //Item已取消
    public static $_status = [
        self::ORDER_DELIVERY_NO     => '未申请发货',
        self::ORDER_DELIVERY_PART   => '部分申请发货',
        self::ORDER_DELIVERY_YES    => '完全申请发货',
        self::ORDER_DELIVERY_CANCEL => 'Item已取消'
    ];

    /**
     * 是否为自建订单
     */
    const CREATE_NO  = 0;   //自动生成订单(否)
    const CREATE_YES = 1;   //真实自建订单(是)

    /**
     * 关联订单
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function order(){
        return $this->belongsTo(CustomerOrder::class, 'order_no');
    }

    /**
     * 关联sku
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function sku(){
        return $this->belongsTo(ProductSku::class, 'psku_id');
    }

    /**
     * 关联发货明细
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function delivery_detail(){
        return $this->hasMany(CustomerDeliveryDetail::class, 'order_detail_id');
    }

    /**
     * 验证申请状态
     * @param $status
     * @return int
     */
    public static function extractStatus($status){
        if(max($status) == 1 || min($status) == 4)return 1;
        return 2;
    }

    /**
     * 获取订单下的平台sku
     * @param $orderNo
     * @param $pskuId
     * @return mixed|string
     */
    public static function getOrderPlatsku($orderNo, $pskuId){
        $platSku = self::query()
            ->where('order_no', $orderNo)
            ->where('psku_id', $pskuId)
            ->value('plat_sku');

        return $platSku ?? '';
    }

    /**
     * 获取订单明细申请状态
     * @param $obj
     * @param int $num
     * @return int
     */
    public static function getOrderDetailStatus($obj, $num = 0){
        $orderDetailStatus = CustomerOrderDetails::ORDER_DELIVERY_NO;
        $obj->apply_num += $num;
        if($obj->order_num > $obj->apply_num){
            $orderDetailStatus = CustomerOrderDetails::ORDER_DELIVERY_PART;
        }else{
            $orderDetailStatus = CustomerOrderDetails::ORDER_DELIVERY_YES;
        }
        if ($obj->apply_num > $obj->order_num) {
            $obj->apply_num = $obj->order_num;
        }
        return $orderDetailStatus; //订单申请状态 (1:未申请 2:部分申请 3:完全申请 4:已取消)
    }

}
